package service

import (
	db "gitee.com/jikey/elk-blog/app/database"
	"gitee.com/jikey/elk-blog/app/model"
	"github.com/jinzhu/gorm"
)

type blog struct {
}

var Blog *blog

// BlogList 获取 blog 列表
func (b *blog) BlogList(PageNum int, PageSize int, maps interface{}) (blog []model.Blog) {
	condition := "left join tk_category on tk_category.colId = tk_blog.catid"
	db.Mysql.Where(maps).Offset((PageNum - 1) * PageSize).Limit(PageSize).Order("ord asc, id desc").Select("tk_blog.*, tk_category.colTitle").Joins(condition).Find(&blog)
	return
}

// GetBy 查询
func (b *blog) GetBy(field, value string) (blog []model.Blog) {
	db.Mysql.Where("? = ?", field, value).First(&blog)
	return
}

// GetArchiveList 获取归档列表
func (b *blog) GetArchiveList(PageNum int, PageSize int, maps interface{}) (blog []model.Blog) {
	db.Mysql.Where(maps).Offset((PageNum - 1) * PageSize).Limit(PageSize).Order("ord asc, id desc").Find(&blog)
	return
}

// BlogDetail 获取 blog 详情
func (b *blog) BlogDetail(id int) (blog *model.Blog, err error) {
	blog = &model.Blog{}
	err = db.Mysql.First(blog, id).Error
	db.Mysql.Model(&blog).Where("id = ?", id).UpdateColumn("views", gorm.Expr("views + ?", 1))
	return
}

// GetBlogTotal 获取 blog 总记录数
func (b *blog) GetBlogTotal(maps interface{}) (count int) {
	db.Mysql.Model(&blog{}).Where(maps).Count(&count)
	return
}

// Create 新增
func (b *blog) Create(model *model.Blog) (err error) {
	err = db.Mysql.Omit("ColTitle").Create(model).Error

	return err
}

// Update 修改
func (b *blog) Update(id string, model *model.Blog) (err error) {
	// err = db.Mysql.Model(&blog{}).Omit("ColTitle").Save(model).Error
	err = db.Mysql.Model(&model).Where("id = ? ", id).Omit("ColTitle").Updates(model).Error

	return err
}

// UpdateField 修改某一字段
func (b *blog) UpdateField(id string, key string, value string) {
	db.Mysql.Model(&blog{}).Where("id = ?", id).Update(key, value)
}

// Delete 删除
func (b *blog) Delete(id string) bool {
	db.Mysql.Where("id = ?", id).Delete(&blog{})

	return true
}

// BlogArchiveList 归档列表
func (b *blog) BlogArchiveList() (archive []model.Archive) {
	sql := "select count(DATE_FORMAT(create_time, '%Y-%m')) as Count, DATE_FORMAT(create_time, '%Y-%m') as Time, create_time as CreateTime from tk_blog group by Time order by Time desc"
	db.Mysql.Raw(sql).Scan(&archive)

	return
}

// GetArchive 归档列表
func (b *blog) GetArchive(PageNum int, PageSize int, ctime string) (blog []model.Blog) {
	db.Mysql.Where("create_time like ?", "%"+ctime+"%").Offset((PageNum - 1) * PageSize).Limit(PageSize).Order("ord asc, id desc").Find(&blog)
	return
}
